package org.hank.wanandroid.ui

import android.os.Bundle
import kotlinx.android.synthetic.main.activity_tree_details.*
import org.hank.commom.base.BaseActivity
import org.hank.wanandroid.R
import org.hank.wanandroid.constants.Constants
import org.hank.wanandroid.listener.OnArticleRecyclerListener
import org.hank.wanandroid.ui.widget.ArticleRecycleWidget
import org.hank.wanandroid.viewmodel.TreeDetailsViewModel

class TreeDetailsActivity : BaseActivity(), OnArticleRecyclerListener {
    override val layoutResId: Int
        get() = R.layout.activity_tree_details

    var title = ""
    var id = 0

    var pageNum = 0
    var totalPage = 0
    var articleRecycleWidget = ArticleRecycleWidget(this)


    val viewModel by getViewModel(TreeDetailsViewModel::class.java) {
        treeDetailsLiveData.observe(it) {
            if (it.datas != null && it.datas!!.size > 0)
                loadingTip.dismiss()
            else
                loadingTip.showEmpty()
            totalPage = it.pageCount
            if(pageNum< totalPage-1)
                pageNum +=1
            articleRecycleWidget.validateData(it.datas)
            dissmissRefresh()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        intent.extras.apply {
            if (this != null) {
                title = getString(Constants.TREE_TITLE, "")
                id = getInt(Constants.TREE_ID, 0)
                tvTitle.text = title

            }
        }
        loadingTip.loading()
        onReload()
        smartrefresh_tree_details.apply {
            setOnRefreshListener {
                onReload()
            }
            setOnLoadMoreListener {
                if(pageNum< totalPage-1)
                    viewModel.getTreeDetails(pageNum,id)
                else{
                    articleRecycleWidget.validateData(null)
                    finishLoadMore()
                }
            }
        }
        var ft = supportFragmentManager.beginTransaction()
        ft.add(R.id.frame_tree_details, articleRecycleWidget)
        ft.commit()
    }

    override fun showToast(msg: String) {
        super.showToast(msg)
        loadingTip.showInternetError()
        dissmissRefresh()
    }

    override fun onReload() {
        pageNum = 0
        viewModel.getTreeDetails(pageNum,id)
        articleRecycleWidget.notifyReload()
    }

    fun dissmissRefresh(){
        smartrefresh_tree_details.finishLoadMore()
        smartrefresh_tree_details.finishRefresh()
    }
}